<template>
  <div>
<!-- 明细改成红色-->
    <h3 class="title">云手机体验质量评测APP-流畅性指标</h3>
<!--    <el-select v-model="value" placeholder="请选择测评类型">-->
<!--      <el-option-->
<!--          v-for="item in options"-->
<!--          :key="item.value"-->
<!--          :label="item.label"-->
<!--          :value="item.value">-->
<!--      </el-option>-->
<!--    </el-select>-->
<!--    <el-date-picker-->
<!--        v-model="value2"-->
<!--        type="datetimerange"-->
<!--        :picker-options="pickerOptions"-->
<!--        range-separator="至"-->
<!--        start-placeholder="开始日期"-->
<!--        end-placeholder="结束日期"-->
<!--        align="right"-->
<!--        style="margin-left: 10px;">-->
<!--    </el-date-picker>-->
<!--    <el-button type="primary" style="margin-left: 10px" class="el-icon-circle-check" @click="searchFluency">查询</el-button>-->
    <el-button type="primary" style="float: right;margin-left: 10px" class="el-icon-download" @click="serverInfoExport">导出</el-button>
    <el-button type="primary" style="float: right" class="el-icon-refresh" @click="refresh">刷新</el-button>
    <title-componet name="云手机流畅性指标" v-if="this.$store.state.titleState"></title-componet>
    <el-table
        class="InfoData"
        :data="this.$dataPage(this.fluencyData,this.currentPage,this.pageSize).pageData"
        :header-cell-style="this.$handleheader"
        border
        :row-style="this.$rowstyle"
        :cell-style="this.$cellstyle"
        @cell-click="detail"
    >
      <el-table-column
          prop="id"
          label="编号"
          width="70"
          sortable
          header-align="center"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="average_fps"
          label="平均帧率"
          width="120"
          sortable
          header-align="center"
      >

      </el-table-column>
      <el-table-column
          prop="frame_shake_rate"
          label="帧抖动率"
          width="100"
          sortable
          header-align="center"
          :formatter="this.$fixTwo"
      >
      </el-table-column>
      <el-table-column
          prop="low_frame_rate"
          label="低帧率"
          width="95"
          sortable
          header-align="center"
          :formatter="this.$fixTwo"
      >
      </el-table-column>
      <el-table-column
          prop="jank_count"
          label="卡顿次数"
          width="95"
          header-align="center"
          sortable
      >
      </el-table-column>
      <el-table-column
          prop="stutter_rate"
          label="卡顿时长占比"
          width="120"
          header-align="center"
          sortable
          :formatter="this.$fixTwo"
      >
      </el-table-column>
      <el-table-column
          prop="frame_interval"
          label="帧间隔"
          width="100"
          header-align="center"
          sortable
          :formatter="this.$fixTwo"
      >
      </el-table-column>
      <el-table-column
          prop="ip"
          label="IP地址"
          width="90"
          header-align="center"
          sortable
      >
      </el-table-column>
      <el-table-column
          prop="port"
          label="端口"
          width="120"
          header-align="center"
      >
      </el-table-column>

      <el-table-column
          prop="time"
          label="测评时间"
          width="150"
          header-align="center"
          sortable
      >
      </el-table-column>
      <el-table-column
          prop="platform_name"
          label="视频/指令流"
          header-align="center"
      />
    </el-table>
    <page :current-page="currentPage" :page-size="pageSize" :total="total" @handleChange="handleCurrentChange"></page>
<!--    <div style="width: 100%; margin: 0px auto;height: 70%;font-weight: 200;font-size: 10px"><p style="line-height: 5px;color: red;font-size: 10px">*操作提示: 点击具体数值可以查看明细</p></div>-->
    <div style="display: flex;justify-content: space-evenly;align-items: center;">
      <div style="width: 30%; margin: 10px auto;font-weight: 200;font-size: 10px;color: red"><p style="font-size: 15px;line-height: 5px">流畅性指标说明:</p><br>（1）平均帧率为视频流或指令流云手机在一段时间内帧率的平均值；<br>（2）帧抖动率为画面帧率的波动幅度；<br>（3）低帧率为画面实时帧率低于标准帧率的比率(%)；<br>（4）卡顿次数为测试过程中卡顿次数(次数/10min)；<br>（5）卡顿时长占比为测试过程中卡顿时长占比(%）；<br>（6）帧间隔为单位时间内两帧之间的传输间隔(ms)。</div>

      <div id="fluencyGraph" style="height: 30vh;width: 60%;margin: 0 auto"></div>
      <!-- 表格下方加注释 -->
    </div>
    <el-dialog
        title="平均帧率-每秒帧率明细"
        :visible.sync="fluencyDialog"
        width="70%"
        :show-close=false>
    <span slot="footer" class="dialog-footer">
    <el-button @click="fluencyDialog = false">关 闭</el-button>
  </span>
    </el-dialog>
    <el-dialog
        title="导出信息填写"
        :visible.sync="exportVisible"
        width="30%"
        :show-close="false"
        :close-on-click-modal="false">

      <el-form ref="form" :model="exportForm" label-width="80px" inline :rules="exportRules">
        <el-form-item label="文件名" prop="name">
          <el-input v-model="exportForm.name"></el-input>
        </el-form-item>
        <el-form-item label="高度" prop="height">
          <el-input v-model="exportForm.height"></el-input>
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="exportForm.width"></el-input>
        </el-form-item>
      </el-form>
      <span style="color: red">{{wh}}</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="exportVisible = false">取 消</el-button>
    <el-button type="primary" @click="exportWord(exportForm.height,exportForm.width,'fluency',exportForm.name),exportVisible = false" v-if="line">确 定</el-button>
        <el-button type="primary" @click="exportWordWithoutGraph('fluency2',exportForm.name),exportVisible = false" v-if="!line">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
import Page from "@/components/page";
import {getWH} from "../components/getWH";
import { Line } from '@antv/g2plot';
import {exportMixin, mixin} from "../components/mixin";
import TitleComponet from "@/components/titleComponet";
import {toDataURL} from "@/components/exportFunction";
import JSZipUtils from "jszip-utils";
import PizZip from "pizzip";
import docxtemplater from "docxtemplater";
import {fluencyList} from "@/api/exp";
import moment from "moment";
export default {
  name: "spquality",
  components:{TitleComponet, Page},
  data(){
    return{
      wh:'',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近1小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近3小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 3);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近12小时',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 12);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近1天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近7天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, ]
      },
      fluencyData:null,
      // total: '',
      // currentPage:1,
      // pageSize: 2,
      //制作弹框显示明细时，告知弹窗当前点的哪一行，根据该行测了多少秒的数据来生成div
      currentId:'',
      options: this.$store.state.testType,
      value: '',
      value2: '',
      line:null,
      exportLine: {
        line: null
      },
      detailData:[],
      fluencyDialog:false,
    }
  },
  created() {
    this.initData()
  },
  mixins:[mixin,exportMixin],
  methods:{
    initData() {
      fluencyList().then(res=>{
      // axios.get(this.$ip2 + '/experience/fluency/list').then(res=>{
        console.log(res);
        this.fluencyData = res.data
        this.total = res.data.length
        //手动增加编号
        for (let i =0;i<res.data.length;i++){
          res.data[i].time = moment(res.data[i].time).format('YYYY-MM-DD HH:mm:ss')
          this.fluencyData[i].id = i + 1
          this.fluencyData[i].average_fps=res.data[i].average_fps + `（明细）`
        }
        // console.log(this.fluencyData[0].each_fps.split(',').length);
      })
    },
    // handleCurrentChange(val) {
    //   // 处理分页点击
    //   this.fluencyCurrentPage = val
    // },
    searchFluency() {
      // 拿数据画图

      this.initChart()
    },
    // 画图
    // label配置属性，在折线的每个点显示数据
    initChart(){
      this.line = new Line('fluencyGraph', {
        data:this.detailData,
        xField: 's',
        yField: 'fps',
        // label:{
        //   visible:true,
        //   offsetX: 6,
        //   offsetY: 6,
        // },
        xAxis: {
          range: [0, 0.98],
          title:{
            text:'s',
            // autoRotate:false,
            position:'end',
            offset:0,
            spacing:5,
            style:{
              fill:'black',
              fontSize:15
            }
          }
        },
        yAxis:{
          title:{
            text:'fps',
            autoRotate:false,
            position:'end',
            offset:0,
            spacing:30,
            style:{
              fill:'black',
              fontSize:15
            }
          },

        }
      });

      this.line.render();
      console.log(this.line)
      // this.dataChange()
    },
    refresh() {
      this.initData()
    },
    detail(row, column, cell, event){
      console.log(row);
      //此代码限制只选fps时生效
      if (column.property==='average_fps'){
        if (this.line){
          this.line.destroy()
        }
        this.detailData =[]
        for (let i =0; i<=row.each_fps.split(',').length;i++) {
          this.detailData.push({
            s: i,
            fps:Number(row.each_fps.split(',')[i-1])
          })
        }
        console.log(this.detailData);
        // this.fluencyDialog = true
        this.currentId = row.id
        this.initChart()
      }
    },
    serverInfoExport() {
      if (this.line) {
        this.wh = getWH('fluencyGraph')
      }
      else {
        this.wh = '没有图表，高宽输入任意值'
      }
      this.exportVisible = true
    },
    getImg() {
      console.log('src', toDataURL(this.line.chart))
      // var img = new Image();
      // img.src = this.chartInstance.getDataURL({
      //   pixelRatio: 2,
      //   backgroundColor: '#fff',
      //   type: 'png'
      // })
      this.exportLine.line = toDataURL(this.line.chart)
      // this.tableData.imgUrl = img.src
      // console.log('src', toDataURL(this.line.chart))
    },
    // Echarts图片处理
    base64DataURLToArrayBuffer(dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, "");
      let binaryString;
      if (typeof window !== "undefined") {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, "base64").toString("binary");
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    },
    //导出为word
    exportWord(height,width,module,name) {
      this.getImg();
        //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
      const ImageModule = require('docxtemplater-image-module-free');
      const _this = this;
      //Word路径，在public文件下(CLI3)
      JSZipUtils.getBinaryContent(`${module}.docx`, function (error, content) {
        if (error) {
          throw error
        }
        let opts = {}
        opts.centered = true;
        opts.fileType = "docx";
        opts.getImage = (tag) => {
          return _this.base64DataURLToArrayBuffer(tag);
        }
        opts.getSize = () => {
          return [width, height]//这里可更改输出的图片宽和高
        }

        let zip = new PizZip(content);
        let doc = new docxtemplater();
        doc.attachModule(new ImageModule(opts));
        doc.loadZip(zip);
        // 这里是设置导出的数据
        doc.setData({
          fluencyData : _this.fluencyData,
          exportLine : _this.exportLine
          // arr: _this.arr // 评语
        })
        try {
          doc.render()
        } catch (error) {
          var e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          }
          console.log(JSON.stringify({
            error: e
          }));
          throw error;
        }
        const out = doc.getZip().generate({
          type: "blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        })
        saveAs(out, `${name}.docx`)
      })
    },
    exportWordWithoutGraph(module,name) {
      // this.getImg();
      // //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
      // const ImageModule = require('docxtemplater-image-module-free');
      const _this = this;
      //Word路径，在public文件下(CLI3)
      JSZipUtils.getBinaryContent(`${module}.docx`, function (error, content) {
        if (error) {
          throw error
        }
        let opts = {}
        opts.centered = true;
        opts.fileType = "docx";
        // opts.getImage = (tag) => {
        //   return _this.base64DataURLToArrayBuffer(tag);
        // }
        // opts.getSize = () => {
        //   return [height, width]//这里可更改输出的图片宽和高
        // }

        let zip = new PizZip(content);
        let doc = new docxtemplater();
        // doc.attachModule(new ImageModule(opts));
        doc.loadZip(zip);
        // 这里是设置导出的数据
        doc.setData({
          fluencyData : _this.fluencyData,
          // exportLine : _this.exportLine
          // arr: _this.arr // 评语
        })
        try {
          doc.render()
        } catch (error) {
          var e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties,
          }
          console.log(JSON.stringify({
            error: e
          }));
          throw error;
        }
        const out = doc.getZip().generate({
          type: "blob",
          mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        })
        saveAs(out, `${name}.docx`)
      })
    },
  },
}
</script>

<style scoped>
</style>
